﻿using System;
using System.Web.UI;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnEntrar_Click(object sender, ImageClickEventArgs e)
    {
        Session["cnpj"] = txtusr.Text;
        if (ValidaUsuario(txtusr.Text, txtSenha.Text))
            Response.Redirect("entrada.aspx");
        else
            Response.Redirect("mensagens.aspx?id=1");
    }

    protected bool ValidaUsuario(string usuario, string senha)
    {
        bool valida = false;
        SqlConnection conexaoIntranet = new SqlConnection(ConfigurationManager.ConnectionStrings["conexao_intranet"].ConnectionString);
        SqlCommand consultaLogin = null;
        SqlDataReader drLogin;
        try
        {
            if (conexaoIntranet != null && conexaoIntranet.State != ConnectionState.Open)
                conexaoIntranet.Open();
            string instrucao = "SELECT "+
                "CodUsuario, Usr, Senha, CadastraFuncao, FeiraProfissoes "+
                "FROM CamaraLogin WHERE USR = @usuario and SENHA = @senha and Excluido = 0";
            consultaLogin = new SqlCommand(instrucao, conexaoIntranet);
            consultaLogin.Parameters.Add("@usuario", usuario);
            consultaLogin.Parameters.Add("@senha", senha);
            drLogin = consultaLogin.ExecuteReader();
            if (drLogin.HasRows)
            {
                valida = true;
                drLogin.Read();
                if (bool.Parse(drLogin["FeiraProfissoes"].ToString()))
                {
                    drLogin.Close();
                    conexaoIntranet.Close();
                    Response.Redirect("mensagens.aspx?id=1");
                }
                Session["codUsuario"] = drLogin["CodUsuario"].ToString();
                Session["login"] = txtusr.Text;
				Session["CadastraFuncao"] = drLogin["CadastraFuncao"].ToString();
            }
            drLogin.Close();
        }
        finally
        {
            conexaoIntranet.Close();
        }
        return valida;
    }
}